import '../../app/services/userServices.dart';
import '../../app/services/messageUtil.dart';
import 'package:get/get.dart';
import 'package:flutter/cupertino.dart';

class AuthMiddleware extends GetMiddleware {
  @override
  RouteSettings? redirect(String? route) {
    final publicRoutes = ['/login', '/register', '/forgot-password'];

    // 允许公开路由直接访问
    if (publicRoutes.contains(route)) return null;

    final userData = UserServices.getUserDataSync();

    if (userData != null) {
      final token = userData["token"] as String?;
      final id = userData["u_id"] as int?;
      if (token != null && token.isNotEmpty && id != null && id > 0) {
        return null; // 验证通过
      }
    }
    
    MessageUtil.showError(message: "请先登录");

    return const RouteSettings(name: "/login");
  }
}
